import {
  CanActivate,
  ExecutionContext,
  ForbiddenException,
  Inject,
  Injectable
} from '@nestjs/common'
import { CasbinModule } from '@ttou/nest-casbin'
import { WinstonLogger, WINSTON_MODULE_LOGGER } from '@ttou/nest-winston'
import { IRequest } from '../interfaces'

@Injectable()
export class RestfulGuard implements CanActivate {
  constructor(
    @Inject(WINSTON_MODULE_LOGGER)
    private logger: WinstonLogger
  ) {}

  canActivate(context: ExecutionContext) {
    const req = context.switchToHttp().getRequest<IRequest>()
    const { url, method } = req
    const user = req.user

    const path = url.split('?')[0]
    const isAllowed = CasbinModule.enforcer.enforceSync(
      user.username,
      path,
      method
    )

    if (isAllowed) {
      return true
    }

    this.logger.warn(
      `${user.username} - ${method} - ${url} 没有权限`,
      RestfulGuard.name
    )

    throw new ForbiddenException()
  }
}
